package org.example.leetCode;

import java.util.Arrays;

/**
 * @Author Qinkai
 * @Description TODO $
 * @Date $ 2019-09-18$
 * @Param $
 * @return $
 **/
public class ThreeSumClosest {
    public static void main(String[] args) {
        int[] ints = {-1, 2, 1, -4};
        int target = 1;
        ThreeSumClosest threeSumClosest = new ThreeSumClosest();
        threeSumClosest.threeSumClosest(ints, target);
    }

    public int threeSumClosest(int[] nums, int target) {
        if (nums.length < 3) {
            return 0;
        }
        int[] sort = Arrays.stream(nums).sorted().toArray();
        int res = sort[0] + sort[1] + sort[2];
        for (int i = 0; i < sort.length - 2; i++) {
            int left = i + 1;
            int right = sort.length - 1;
            while (left < right) {
                int sum = sort[left] + sort[right] + sort[i];
                if (Math.abs(res - target) > Math.abs(sum - target)) {
                    res = sum;
                }
                if (sum > target) {
                    right--;
                } else if (sum < target) {
                    left++;
                } else {
                    return sort[i] + sum;
                }
            }
        }
        return res;
    }
}
